package com.steamedfish.auctioncloudprocess.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.steamedfish.auctioncloudprocess.entiry.AuctionRegisterEntity;
import com.steamedfish.auctioncloudprocess.entiry.UserEntiry;
import com.steamedfish.auctioncloudprocess.feign.client.AdMailClient;
import com.steamedfish.auctioncloudprocess.feign.client.SecurityOAuth2Client;
import com.steamedfish.auctioncloudprocess.mapper.AuctionRegisterMapper;
import lombok.SneakyThrows;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 查询指定商品的订阅人，通知其参与拍卖
 *
 * @param id
 * @return int
 */
public class StartAuctionAlertTask implements Job {

    @Autowired
    private AuctionRegisterMapper auctionRegisterMapper;

    @Autowired
    private AdMailClient adMailClient;

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private SecurityOAuth2Client securityOAuth2Client;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final static String name = "startAuctionAlert";
    private final static String  group = "process2";


    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.info("StartAuctionAlertTask被执行");

        //获取订阅指定id的用户mail
        String id = (String) jobExecutionContext.getMergedJobDataMap().get("id");
        List<String> mails = getMails(id);
        String[] mailss = mails.toArray(new String[mails.size()]);

        //发送邮件
        adMailClient.sendAlertMail(id, mailss);
        scheduler.deleteJob(new JobKey(name,group));
    }

    public static JobDetail getJobDetail(String id){
        JobDetail jobDetail = JobBuilder.newJob(StartAuctionAlertTask.class).withIdentity(name, group).build();
        jobDetail.getJobDataMap().put("id",id);
        return jobDetail;
    }

    public static Trigger getTrigger(Date startDate){
        SimpleTrigger simpleTrigger=TriggerBuilder.newTrigger()
                .withIdentity(name,group)
                .startAt(startDate)
                .withSchedule(
                        SimpleScheduleBuilder.simpleSchedule()
                                .withIntervalInSeconds(0)
                                .withRepeatCount(0))
                .build();
        return simpleTrigger;
    }

    /**
     * 通过商品id查询订阅了改商品的所有的用户mail
     *
     * @param id
     * @return int
     */
    public List<String> getMails(String id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("item_id", id);
        List<AuctionRegisterEntity> auctionRegisterEntitys = auctionRegisterMapper.selectList(queryWrapper);

        List<String> mails = new ArrayList<>();
        for (AuctionRegisterEntity a : auctionRegisterEntitys) {
            mails.add(getMailFromAuctionRegisterEntity(a));
        }
        return mails;
    }


    /**
     * 通过订阅信息查询到mail
     *
     * @param id
     * @return int
     */
    private String getMailFromAuctionRegisterEntity(AuctionRegisterEntity auctionRegisterEntity) {
        UserEntiry userEntiry = securityOAuth2Client.getUserInfo(auctionRegisterEntity.getUserId());
        String mail = userEntiry.getMail();
        return mail;
    }


}